/*******************************************************************************
 * Copyright (c) 2011 Gijs de Vries aka Janoz.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Gijs de Vries aka Janoz - initial API and implementation
 ******************************************************************************/
/* COPYRIGHT (C) 2008 Gijs de Vries. All Rights Reserved. */
package com.janoz.httpd;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Enumeration of the different mimetypes.
 * 
 * @author Gijs de Vries
 *
 */
public enum MimeType {
	HTML ("text/html","html","htm"),
	XML  ("text/xml","xml"),
	CSS  ("text/css","css"),
	TEXT ("text/plain","txt"),
	JPEG ("image/jpeg","jpg","jpeg"),
	PNG  ("image/png","png"),
	GIF  ("image/gif","gif"),
	ICO  ("image/x-icon","ico"),
	BIN  ("application/octet-stream");
	
	
	private final String mimeType;
	private final String[] extentions;
	
	private static final Map<String, MimeType> extentionsMap = new HashMap<String,MimeType>();
	static{
		for (MimeType mimeType : EnumSet.allOf(MimeType.class)) {
			for (String extention : mimeType.extentions) {
				extentionsMap.put(extention, mimeType);
			}
		}
	}
	
	/**
	 * 
	 * @param mimeType the mimetype as used in the http headers
	 */
	MimeType(String mimeType, String... extentions) {
		this.mimeType = mimeType;
		this.extentions = extentions;
	}

	/**
	 * Adds the content type to the headers of a http response.
	 * @param headers the headers the mimetype should be added to
	 */
	public void addToHeader(Properties headers) {
		headers.setProperty("Content-Type", mimeType);
	}

	/**
	 * Adds the content type to the headers of a http response.
	 * @param headers the headers the mimetype should be added to
	 * @param charset character set used
	 */
	public void addToHeader(Properties headers, String charset) {
		headers.setProperty("Content-Type", mimeType + "; charset="+charset);
	}

	/**
	 * Return the right mimetype based on the file extension.
	 * @param extension the file extension
	 * @return the mimetype
	 */
	public static MimeType getMimeType(String extension) {
		MimeType result = extentionsMap.get(extension.toLowerCase());
		return result!=null?result:BIN;
	}
}
